package legacy

import "fmt"

// NewPacket 创建新的数据包
func NewPacket(fontName string, fontSize, fontWidth, charSpacing, rotation uint32,
	bold, italic bool, style uint32, x, y uint32, text string) (*Packet, error) {
	
	// 验证参数
	if err := validateParameters(fontSize, fontWidth, charSpacing, rotation, x, y, text); err != nil {
		return nil, fmt.Errorf("参数验证失败: %w", err)
	}
	
	packet := &Packet{
		StartMarker:  [4]byte{StartMarker1, StartMarker2, StartMarker3, StartMarker4},
		Sequence:     getNextSequence(),
		PacketType:   PacketType,
		FontSize:     fontSize,
		FontWidth:    fontWidth,
		CharSpacing:  charSpacing,
		Rotation:     rotation,
		Style:        style,
		XCoord:       x,
		YCoord:       y,
		Text:         []byte(text),
		StopMarker:   [2]byte{StopMarker1, StopMarker2},
	}
	
	// 设置字体名称（UTF8编码，不足32字节补零）
	copy(packet.FontName[:], []byte(fontName))
	
	// 设置加粗和斜体标志
	if bold {
		packet.Bold = 1
	}
	if italic {
		packet.Italic = 1
	}
	
	// 计算数据包长度（整个包的长度）
	packet.PacketLength = uint32(MinPacketSize + len(packet.Text))
	
	// 计算校验和
	packet.Checksum = packet.calculateChecksum()
	
	return packet, nil
}

// validateParameters 验证参数范围
func validateParameters(fontSize, fontWidth, charSpacing, rotation, x, y uint32, text string) error {
	if fontSize < 12 || fontSize > 1000 {
		return fmt.Errorf("字号超出范围: %d (应在12-1000之间)", fontSize)
	}
	if fontWidth < 12 || fontWidth > 1000 {
		return fmt.Errorf("字宽超出范围: %d (应在12-1000之间)", fontWidth)
	}
	if charSpacing > 999999 {
		return fmt.Errorf("字间隔超出范围: %d (应在0-999999之间)", charSpacing)
	}
	if rotation > 90 {
		return fmt.Errorf("旋转角度超出范围: %d (应在0-90之间)", rotation)
	}
	if x > 999999 {
		return fmt.Errorf("X坐标超出范围: %d (应在0-999999之间)", x)
	}
	if y > 999999 {
		return fmt.Errorf("Y坐标超出范围: %d (应在0-999999之间)", y)
	}
	textLen := len([]byte(text))
	if textLen < MinTextLength || textLen > MaxTextLength {
		return fmt.Errorf("文本长度超出范围: %d (应在%d-%d之间)", textLen, MinTextLength, MaxTextLength)
	}
	return nil
}

// getNextSequence 获取下一个序列号
func getNextSequence() uint16 {
	sequenceCounter++
	return sequenceCounter
}